package com.example.wxback.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.wxback.model.MessageInfo;
import com.example.wxback.model.UserInfo;
import com.example.wxback.push.PushUtil;
import com.example.wxback.redis.JedisDao;
import com.example.wxback.service.UserMessageDetailService;
import com.example.wxback.service.UserMessageService;
import com.example.wxback.service.WxUserService;
import com.example.wxback.util.*;
import com.example.wxback.util.constants.Constants;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/wx/message")
public class UserMessageController {

    @Autowired
    private JedisDao jedisDao;

    @Autowired
    WxUserService wxUserService;

    @Autowired
    UserMessageService userMessageService;

    @Autowired
    UserMessageDetailService userMessageDetailService;

    @PostMapping("/upload")
    public JSONObject uploadMessage(@RequestBody MessageInfo messageInfo) {
        UserInfo masterUserInfo = null;
//        if (jedisDao.exist(RedisUtil.getUserKey(messageInfo.getUserId()))) {
//            String userJsonData = jedisDao.getValue(messageInfo.getUserId() + "");
//            if (StringUtils.isNotBlank(userJsonData)){
//                masterUserInfo = JsonUtils.jsonToPojo(userJsonData, UserInfo.class);
//            }
//        }
        if (masterUserInfo == null) {
            masterUserInfo = wxUserService.getUserByChildId(messageInfo.getUserId());
//            if (masterUserInfo != null) {
//                jedisDao.setValue(RedisUtil.getUserKey(messageInfo.getUserId()), JsonUtils.objectToJson(masterUserInfo));
//                jedisDao.setExpireTime(RedisUtil.getUserKey(messageInfo.getUserId()), Constants.REDIS_EXPIRE_TIME_DAY * 5);
//            }
        }
        if (masterUserInfo == null) {
            return CommonUtil.errorJson("控制端不存在");
        } else if (StringUtils.isBlank(masterUserInfo.getActivateCode())) {
            return CommonUtil.errorJson("控制端未激活");
        } else if (DateUtil.getCurrentTime().compareTo(DateUtil.getTimeFromDate(masterUserInfo.getExpirationTime())) > 0) {
            return CommonUtil.errorJson("激活码已过期");
        } else if (masterUserInfo.getEnable() == 0) {
            return CommonUtil.errorJson("控制端已被禁用");
        }

        MessageInfo messageInfoTemp = userMessageService.getMessage(messageInfo);
        messageInfo.setCreateDate(new Date());
        messageInfo.setUpdateDate(new Date());
        if (messageInfoTemp == null) {
            userMessageService.insertMessage(messageInfo);
        } else {
            messageInfo.setUpdateDate(new Date());
            userMessageService.updateMessage(messageInfo);
        }
        messageInfoTemp = userMessageService.getMessage(messageInfo);
        if (messageInfoTemp != null) {
            messageInfo.setConversationId(messageInfoTemp.getId());
        }
        if (userMessageDetailService.insertMessage(messageInfo)) {
            try {
                PushUtil.sendAndroidCustomizedcast(masterUserInfo.getDeviceToken());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return CommonUtil.successJson("添加成功");
        } else {
            return CommonUtil.errorJson("消息添加失败");
        }
    }

    @GetMapping("/menu")
    public JSONObject getMessageMenuList(@Param("masterId") Integer masterId) {
        UserInfo userInfo = wxUserService.getUser(masterId);
        if (StringTools.isNullOrEmpty(userInfo)) {
            return CommonUtil.errorJson("用户不存在");
        } else if (StringTools.isNullOrEmpty(userInfo.getChildId())) {
            return CommonUtil.successJson("未绑定用户");
        }
        List<MessageInfo> messageInfoList = userMessageService.getMessageList(userInfo.getChildId());
        return CommonUtil.successJson(messageInfoList);
    }

    @GetMapping("/list")
    public JSONObject getMessageDetailList(@Param("conversationId") Integer conversationId) {
        List<MessageInfo> messageInfoList = userMessageDetailService.getMessageList(conversationId);
        return CommonUtil.successJson(messageInfoList);
    }

    @DeleteMapping("/expired")
    public JSONObject deleteExpiredMessage() {
        // 删除两天前消息记录
        Date beforeTwoDate = DateUtil.plusDay(new Date(), -2);
        userMessageDetailService.deleteExpiredMessage(beforeTwoDate);
        return CommonUtil.successJson("删除成功");
    }
}
